﻿using HDLogCenter.Bll.Services;
using HDLogCenter.Infrastructure.Models;
using HDLogCenter.Infrastructure.Models.Inputs;
using Microsoft.AspNetCore.Mvc;

namespace HDLogCenter.Controllers
{
    public class HomeController : Controller
    {
        private readonly LogService _logService;
        private readonly ProjectConfigService _projectConfigService;

        public HomeController(LogService logService, ProjectConfigService projectConfigService)
        {
            _logService = logService;
            _projectConfigService = projectConfigService;
        }

        public async Task<IActionResult> Index()
        {
            try
            {
                // 获取统计数据
                var totalLogs = await _logService.GetLogCountAsync(new SearchLogsInput() { });
                var totalProjects = await _projectConfigService.GetAllProjectsAsync();
                var todayLogs = await _logService.GetLogCountAsync(new SearchLogsInput() 
                {
                    StartTime = DateTime.Today
                });
                var errorLogs = await _logService.GetLogCountAsync(new SearchLogsInput()
                {
                    Level = 4
                }); // 假设4是Error级别

                ViewBag.TotalLogs = totalLogs;
                ViewBag.TotalProjects = totalProjects.Count();
                ViewBag.TodayLogs = todayLogs;
                ViewBag.ErrorLogs = errorLogs;

                // 获取最近日志
                var recentLogs = await _logService.GetAllLogsAsync();
                ViewBag.RecentLogs = recentLogs;

                // 获取项目状态
                ViewBag.Projects = totalProjects;

                return View();
            }
            catch (Exception ex)
            {
                // 如果数据库连接失败，显示错误信息
                ViewBag.Error = ex.Message;
                ViewBag.TotalLogs = 0;
                ViewBag.TotalProjects = 0;
                ViewBag.TodayLogs = 0;
                ViewBag.ErrorLogs = 0;
                ViewBag.RecentLogs = new List<LogDto>();
                ViewBag.Projects = new List<AppConfigModel>();
                return View();
            }
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View();
        }
    }
}